<?php
trait BpfTrait {

  protected function getIni($key, $defaultValue = '') {
    return Azalea\Config::get($key, $defaultValue);
  }

  protected function setIni($key, $value = '') {
    return Azalea\Config::set($key, $value);
  }

  protected function loadLibrary($filePath)
  {
    Azalea\Loader::load(Azalea\APPROOT . 'lib/' . $filePath);
  }

  protected function getView()
  {
    static $smarty = null;
    if (!isset($smarty)) {
      $filePath = $this->getIni('theme', 'default');
      $this->loadLibrary('smarty/Smarty.class.php');
      $smarty = new Smarty();
      $router = $this->getRouter();
      $path = join('/', $router['folder'] ? [$router['folder'], $router['controller'], $router['action']] : [$router['controller'], $router['action']]);
      $smarty->setTemplateDir(SYSPATH . 'views/' . $filePath);
      $smarty->setCompileDir(VARPATH . '/templates_c');
      $smarty->setConfigDir(CNFPATH);
      $smarty->setCacheDir(VARPATH . '/cache');
      $smarty->addPluginsDir(LIBPATH . '/smarty_plugins');
      $smarty->assign('tpldir', urlStatic(''));
      $smarty->assign('router', $router);
      $smarty->assign('path', $path);
    }
    return $smarty;
  }

  public function getRouter()
  {
    return Azalea\Bootstrap::getRouter();
  }

  protected function addJs($filename)
  {
    $smarty = $this->getView();
    if (!is_array($filename)) {
      $filename = array($filename);
    }
    foreach ($filename as $fn) {
      if (strcasecmp(substr($fn, 0, 7), 'http://') && strcasecmp(substr($fn, 0, 8), 'https://')) {
        $fn = urlStatic('/' . trim($fn, '/'));
      }
      $smarty->append('html_js', $fn);
    }
  }

  protected function addCss($filename)
  {
    $smarty = $this->getView();
    if (!is_array($filename)) {
      $filename = array($filename);
    }
    foreach ($filename as $fn) {
      if (strcasecmp(substr($fn, 0, 7), 'http://') && strcasecmp(substr($fn, 0, 8), 'https://')) {
        $fn = urlStatic(trim($fn, '/'));
      }
      $smarty->append('html_css', $fn);
    }
  }

  protected function logfile($message)
  {
    $this->_classname = $this->_classname ?? strtolower(get_called_class());
    access($message, $this->_classname);
  }

  protected function gotoUrl($url, $refererFirst = false)
  {
    if ($refererFirst && !empty($_SERVER['HTTP_REFERER'])) {
      $this->res->gotoUrl($_SERVER['HTTP_REFERER']);
    }
    $this->res->gotoUrl($url);
  }
}
